const Base = require('./base.js');
const fs = require('fs');
const _ = require('lodash');

module.exports = class extends Base {
  async infoAction() {
    const userInfo = await this.model('user').where({
      mobile: '15989389319'
    }).find();
    delete userInfo.password;
    return this.json(userInfo);
  }

  /**
   * 保存用户头像
   * @returns {Promise.<void>}
   */
  async saveAvatarAction() {
    const avatar = this.file('avatar');
    if (think.isEmpty(avatar)) {
      return this.fail('保存失败');
    }

    const avatarPath = think.RESOURCE_PATH + '/static/user/avatar/1.' + _.last(_.split(avatar.path, '.'));

    fs.rename(avatar.path, avatarPath, function (res) {
      return this.success();
    });
  }

  /**
   * 绑定用户和内部OA系统
   * @returns {Promise.<void>}
   */
  async reletionAction() {
    const userId = think.userId;
    let reletion_dode = this.post('reletion_dode');
    think.logger.info('reletion_dode=' + reletion_dode);
    think.logger.info('userId=' + userId);
    const sysUser = await this.model('sys_user').where({
      user_id: reletion_dode
    }).find();
    if (think.isEmpty(sysUser)) {
      return this.fail(400, '账号不正确');
    }
    think.logger.info('admin.mobile=' + sysUser.mobile);

    // 更新登录信息
    let user = await this.model('csshop_user').where({
      id: userId
    }).update({
      last_login_time: parseInt(new Date().getTime() / 1000),
      rele_user_id: reletion_dode,
      mobile: sysUser.phone
    });
    think.logger.info('user=' + user);
    think.logger.info('sysUser=' + sysUser);
    think.logger.info(sysUser);
    const sysUserInfo = await this.model('v_sys_user').where({
      user_id: reletion_dode
    }).find();

    think.logger.info(sysUserInfo);
    think.logger.info('ddddddddddddddddddddddddddd==' + sysUserInfo.role_name);

    const csshopUser = await this.model('csshop_user').where({
      id: userId
    }).find();

    csshopUser.role_name = sysUserInfo.role_name;
    csshopUser.company_name = sysUserInfo.company_name;
    csshopUser.office_name = sysUserInfo.office_name;
    csshopUser.company_id = sysUserInfo.company_id;
    csshopUser.office_id = sysUserInfo.office_id;
    csshopUser.name = sysUserInfo.name;
    csshopUser.role_en_name = sysUserInfo.role_en_name;

    return this.success({
      token: think.token,
      code: '0',
      userInfo: csshopUser
    });

  }
};